<template>
	<view class="all" >
		<!-- v-if="longitude" -->
		<!-- 头部 -->
		<view class="bg" :style="{ backgroundImage: 'url(' + asyncImgs.mch_m_admin.bg + ')' }">
			<view class="search-nav" :style="{ paddingTop: statusBarHeight + 'px', }">
				<view class="nav-head" :style="{ height: '80rpx'}">
					<view class="back-icon" @click="goBack">
						<image :src="asyncImgs.images.left_arrow_icon" mode="" />
					</view>
					<view class="search-input flex-y-center" :style="{ borderRadius: '40rpx' }" @click="goSearch">
						<u-search bg-color="#fff" placeholder="关键字/房名/酒店" :clearabled="true" :show-action="false"
							style="width: 100%" :disabled="true"></u-search>
					</view>
				</view>
			</view>
			<view :style="{ paddingTop: statusBarHeight + 'px', paddingBottom: '80rpx', }"></view>
		</view>
		<!-- 模板1 -->
		<view class="" v-if="template==0">
			<templateOne :newList="newList" :obj="obj" :dis="dis"></templateOne>
			<view style="padding:30rpx 0">
				<u-loadmore :status="noMore ? 'nomore': 'loadmore'" />
			</view>
		</view>
		<!-- 模板2 -->
		<view class="" v-else>
			<templateTwo :cat_List1="cat_List" :obj="obj" :mch_id="mch_id"></templateTwo>
		</view>

		<!-- 购物车数量--跳转 -->
		<view class="cat" @click="goCat">
			<u-icon name="shopping-cart" size="50rpx" color="#fff"></u-icon>
			<view class="num">
				{{ cartNum < 100 ? cartNum : "99+" }}
			</view>
		</view>
		<goodsAddCart @over="handleOver" :good="good"></goodsAddCart>
	</view>
</template>

<script>
	import templateOne from "./components/templateOne.vue";
	import templateTwo from "./components/templateTwo.vue";
	import goodsAddCart from "@/components/diyNew/goodsAddCart/index.vue";
	export default {
		components: {
			templateOne,
			templateTwo,
			goodsAddCart
		},
		data() {
			return {
				noMore: false,
				page: 1,
				limit: 20,
				newList: [],
				template: 0,
				mch_id: 0,
				// 商家头部数据
				obj: {},
				longitude: "",
				latitude: "",
				one_store_switch_store: false,
				dis: '',
				cat_List: [],
				good: {},
				formattedDate:'',
				back:false,
			};
		},
		async onLoad(option) {
			if(option.mch_id){
				this.mch_id = option.mch_id
			}else{
				this.mch_id =uni.getStorageSync("mch_id");
				if(option.login){
					uni.removeStorageSync("mch_id")
					console.log('我删除了')
				}
				this.back=true
				 console.log('入驻商进入的mch_id',this.mch_id)
			}
			
			uni.$on("diyAddGood1", this.toAddcart);
			function getFormattedDate() {
				const now = new Date();
				const year = now.getFullYear();
				const month = String(now.getMonth() + 1).padStart(2, '0'); 
				const day = String(now.getDate()).padStart(2, '0');
				return `${year}${month}${day}`;
			}
			this.formattedDate = getFormattedDate();
			 const storedDate = uni.getStorageSync('todayDate'+option.mch_id);
			 
			 
			if(this.formattedDate==storedDate){
				console.log('已经调取，不掉接口')
			}else{
				console.log('存储数据，调取接口')
				uni.setStorageSync('todayDate'+option.mch_id, this.formattedDate);
				this.getMchFangke()
			}
			// 判断是否获取定位
			this.one_store_switch_store = this.$store.getters.one_store_switch_store;
			try {
				let res = await this.$store.dispatch("getLocation");
				this.longitude = res.longitude;
				this.latitude = res.latitude;
				// 获取购物车商品
				this.getCat()
				this.getList()
				this.getMch()
			} catch (error) {}
		},
		onReachBottom() {
			this.getList(true)
		},
		onUnload() {
		    // uni.removeStorageSync("mch_id")
		    // console.log('页面关闭');
		},
		computed: {
			cartNum() {
				return this.$store.getters.cartNum;
			},
		},
		watch: {
			newList: {
				handler(newVal, oldVal) {
					let map = new Map();
					this.cat_List.forEach(item => {
						if (map.has(item.goods_id)) {
							map.set(item.goods_id, map.get(item.goods_id) + item.num);
						} else {
							map.set(item.goods_id, item.num);
						}
					});

					// 遍历 newList 并更新 catNum
					this.newList.forEach(item => {
						// 将 id 转换为数字进行匹配
						const idAsNumber = Number(item.id);
						if (map.has(idAsNumber)) {
							item.catNum = map.get(idAsNumber);
						} else {
							item.catNum = 0; // 如果没有匹配的 goods_id，确保 catNum 为 0
						}
					});
				},
				deep: true
			},
			cat_List: {
				handler(newVal, oldVal) {
					let map = new Map();
					this.cat_List.forEach(item => {
						if (map.has(item.goods_id)) {
							map.set(item.goods_id, map.get(item.goods_id) + item.num);
						} else {
							map.set(item.goods_id, item.num);
						}
					});

					// 遍历 newList 并更新 catNum
					this.newList.forEach(item => {
						// 将 id 转换为数字进行匹配
						const idAsNumber = Number(item.id);
						if (map.has(idAsNumber)) {
							item.catNum = map.get(idAsNumber);
						} else {
							item.catNum = 0; // 如果没有匹配的 goods_id，确保 catNum 为 0
						}
					});
				},
				deep: true
			}
		},
		methods: {
			async getMchFangke(){
				var res = await this.$allrequest.mch_store.mchFangke({
					date:this.formattedDate,
					mch_id:this.mch_id
				});
				if (res.code == 0) {
					
				}
			},
			// 规格获取
			handleOver(value) {
				console.log('value', value)
				if (value) {
					this.getCat()
				}
			},
			toAddcart(e) {
				this.good = JSON.parse(JSON.stringify(e));
				setTimeout(() => {
					this.good = {};
				}, 1);
			},

			// 获取购物车商品
			getCat() {
				this.$allrequest.goodscart.getCartList().then((res) => {
					if(res.data.mch_list[0]){
						this.cat_List = res.data.mch_list[0].list 
					}
					
				})
			},
			// 获取入驻商信息
			async getMch() {
				var res = await this.$allrequest.mch_store.mchMsg({
					mch_id: this.mch_id,
					lng: this.longitude,
					lat: this.latitude
				});
				if (res.code == 0) {
					this.obj = res.data
					this.template = res.data.home_type
					this.dis = res.dis
					console.log('this.dis', res.dis)
				}
			},
			// 获取模板列表数据
			async getList(isBottom) {
				// 已经到底
				if (this.noMore) return
				// 触底更新数据
				if (isBottom) {
					this.page++
				}
				var res = await this.$allrequest.mch_store.goodList({
					page: this.page,
					limit: this.limit,
					mch_id: this.mch_id
				});
				if (res.code == 0) {
					res.data.list = res.data.list.map(item => ({
						...item,
						catNum: 0
					}));
					this.newList.push(...res.data.list)
					// this.noMore = parseInt(res.data.row_count, 10) <= res.data.page_count * this.page
					this.noMore = this.newList.length >= parseInt(res.data.row_count, 10)
				}
			},

			// 点击搜索
			goSearch() {
				uni.navigateTo({
					url: `/other/search/searchPage?mch_id=${this.mch_id}`
				})
			},
			// 返回上一页
			goBack() {
				uni.removeStorageSync("mch_id")
				if(this.back){
					uni.switchTab({
						url:"/pages/home/home"
					})
					return
				}
				uni.navigateBack();
			},
			// 跳转购物车
			goCat() {
				uni.switchTab({
					url: '/pages/shoppingcart/shoppingcart'
				});

			},
		},
	};
</script>

<style scoped lang="scss">
	.all {
		width: 750rpx;
		background: #F2F2F2;
		min-height: 100vh;
	}

	.bg {
		background-position: center center;
		background-size: contain;
		background-repeat: no-repeat;
		height: 432rpx;
	}

	.search-nav {
		width: 100%;
		font-family: PingFang SC;
		position: fixed;
		left: 0;
		top: 0;
		z-index: 201;

		.nav-head {
			display: flex;
			align-items: center;

			.back-icon {
				width: 90rpx;
				display: flex;
				justify-content: center;
				align-items: center;

				image {
					width: 36rpx;
					height: 36rpx;
					display: block;
				}
			}

			.search-input {
				flex: 1;
				// #ifndef H5 || APP-PLUS
				padding-right: 30%;
				// #endif
				overflow: hidden;
				height: 100%;

				input {
					width: 100%;
					height: 100%;
					background: #f2f2f2;
					font-size: 28rpx;
					font-weight: 400;
					padding: 0 20rpx;
					box-sizing: border-box;
				}
			}
		}
	}

	.search-nav::after {
		content: "";
		width: 100%;
		height: 100%;
		background-color: #ffffff;
	}

	.cat {
		width: 90rpx;
		height: 90rpx;
		background: linear-gradient(90deg, #F22407 0%, #F84D17 100%);
		box-shadow: 0rpx 6rpx 12rpx 2rpx rgba(0, 0, 0, 0.16);
		border-radius: 120rpx 120rpx 120rpx 120rpx;
		display: flex;
		align-items: center;
		justify-content: center;
		position: fixed;
		bottom: 96rpx;
		right: 48rpx;

		.num {
			position: absolute;
			top: -8rpx;
			right: -8rpx;
			width: 36rpx;
			height: 36rpx;
			background: #F62F1F;
			border: 2rpx solid #FFFFFF;
			border-radius: 120rpx;
			color: #fff;
			font-size: 20rpx;
			display: flex;
			align-items: center;
			justify-content: center;
		}
	}
</style>